package com.lyj.ai.controller;

import groovy.util.logging.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * 聊天模型
 */
@Slf4j
@RestController
@RequestMapping("/ai")
class ChatController {

    @Autowired
    ChatClient chatClient;

    @Autowired
    ChatModel chatModel;

    /**
     * 一次性返回所有内容
     * @param msg
     * @return
     */
    @GetMapping("/chat")
    String generation(@RequestParam(value = "msg",defaultValue = "讲个笑话") String msg) {
        return this.chatClient.prompt()
                // msg：录入的信息
                .user(msg)
                // 请求大模型
                .call()
                // 返回文本
                .content();
    }

    /**
     * 流式响应
     *
     * @param msg
     * @return
     */
    @GetMapping(value = "/stream" , produces = "text/markdown;charset=UTF-8")
    public Flux<String> stream(@RequestParam(value = "msg",defaultValue = "讲个笑话") String msg ) {
        return  this.chatClient.prompt()
                // msg：录入的信息
                .user(msg)
                // 请求大模型
                .stream()
                // 返回文本
                .content();
    }



    @GetMapping(value = "/chatModel")
    public  String chatModel(@RequestParam(value = "msg",defaultValue = "讲个笑话") String msg ) {

        ChatResponse response = chatModel.call(
                new Prompt(
                        msg,
                        OpenAiChatOptions.builder()
                                .model("gpt-4o")
                                .temperature(0.4)
                                .build()
                ));
        return response.getResult().getOutput().getText();
    }
}